package com.mobi.Survey.lib.db;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.mobi.Survey.lib.model.AggregateResultPojo;
import com.mobi.Survey.lib.model.Pojo;
import com.mobi.Survey.lib.utils.Helper;

/**
 * 
 * <p>
 * <b>Author:</b> Yahya Arshad
 * <p>
 * <b>Company:</b> Mobi Media Soft
 * <p>
 * <b> Website:</b> www.mobimediasoft.com
 * <p>
 * AggregateResultTable.java This class provides methods for operation on
 * aggregate result table(graph data table)
 * 
 */
public class AggregateResultTable extends AbstractTable {

	public static final String TABLE = "aggregate_data";
	public static final String COL_ID = "_id";

	public static final String COL_SURVEY_ID = "survey_id";
	public static final String COL_SEQUANCE_NO = "seq_no";
	public static final String COL_CTRL_TYPE = "ctrl_type";
	public static final String COL_RATING = "rating";
	public static final String COL_COUNT = "count";
	public static final String COL_SURVEY_KEY = "survey_key";
	public static final String COL_TITLE = "title";

	public AggregateResultTable() {

	}

	/**
	 * 
	 * @param objs
	 *            List of objects of Aggregate result each object in collection
	 *            represents Graph data of a particular Controls
	 * @param surveyId
	 * @return
	 */
	public long insertRow(List<AggregateResultPojo> objs, long surveyId) {
		SQLiteDatabase db = dbHelper.getWritableDatabase();

		for (Pojo obj : objs) {
			AggregateResultPojo arp = (AggregateResultPojo) obj;

			ContentValues cv = new ContentValues();
		 
				cv.put(COL_SURVEY_ID, surveyId);
				cv.put(COL_CTRL_TYPE, arp.getCtrlType());
				cv.put(COL_RATING, arp.getRating());
				cv.put(COL_COUNT, arp.getCount());
				cv.put(COL_SURVEY_KEY, arp.getSurveyKey());
				cv.put(COL_SEQUANCE_NO, arp.getSequanceNo());
				cv.put(COL_TITLE, arp.getTitle());
				db.insert(TABLE, null, cv);
				cv.clear();
			 

		}
		return objs.size();

	}

	/**
	 * 
	 * @param sKey
	 * @return If graph data with given key exist already in db return value
	 *         greater than 0
	 */
	public int isNew(String sKey) {
		SQLiteDatabase db = dbHelper.getReadableDatabase();
		Cursor cursor = db.query(TABLE, new String[] { COL_SURVEY_ID },
				COL_SURVEY_KEY + " Like '" + sKey + "' ", null, null, null,
				null);
		int id = -1;
		if (cursor != null) {

			if (cursor.moveToFirst() && (cursor.getCount() > 0)) {
				id = cursor.getInt(0);
			}

			cursor.close();
			cursor = null;
		}
		return id;

	}

	public AggregateResultTable(Context ctx) {
		super(ctx);
	}

	/**
	 * 
	 * @param surveyId
	 *            Valid survey id for which retrieve Survey Graph data
	 * @return
	 */
	public List<AggregateResultPojo> getAggregateResult(long surveyId) {

		List<AggregateResultPojo> aggregate = new ArrayList<AggregateResultPojo>();
		SQLiteDatabase db = dbHelper.getReadableDatabase();
		Cursor cursor = db.query(TABLE, null, COL_SURVEY_ID + " = ? ",
				new String[] { surveyId + "" }, null, null, null);
		if (cursor != null) {

			AggregateResultPojo arp = new AggregateResultPojo();

			if (cursor.moveToFirst()) {
				boolean firstTime = true;
				int prevSeqNo = 0;

				do {

					long id = cursor.getLong(0);
					byte ctr_type = (byte) cursor.getInt(2);
					String ctrl_rating = cursor.getString(3);
					double count = Helper.toDouble(cursor.getString(4));
					String surveyKey = cursor.getString(5);
					String title = cursor.getString(7);
					int seqNo = cursor.getInt(6);
					// We are tracking if we found new sequance number this
					// means new control data is started
					if (firstTime) {
						prevSeqNo = seqNo;
					}
					if (seqNo != prevSeqNo) {
						prevSeqNo = seqNo;

						// arp.getRatings().remove(arp.getRatings().size() - 1);
						// arp.getCounts().remove(arp.getCounts().size() - 1);
						aggregate.add(arp);
						arp = new AggregateResultPojo();
					}
					firstTime = false;

					arp.setId(id).setCtrlType(ctr_type).setSurveyKey(surveyKey)
							.setTitle(title);
					arp.getRatings().add(ctrl_rating);
					arp.getCounts().add(count);

				} while (cursor.moveToNext());
				if (arp != null) {
					aggregate.add(arp);
					arp = null;
				}

			}

			cursor.close();
			cursor = null;
		}

		return aggregate;
	}

	@Override
	public boolean deleteRow(long surveyId) {
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		return db.delete(TABLE, COL_SURVEY_ID + "=? ", new String[] { surveyId
				+ "" }) > 0;

	}

	@Override
	public boolean createTable(SQLiteDatabase sqliteDb) {
		String query = "create table " + TABLE + "( " + COL_ID
				+ " integer primary key autoincrement, " + COL_SURVEY_ID
				+ " integer not null,  " + COL_CTRL_TYPE
				+ " integer not null, " + COL_RATING + " text, " + COL_COUNT
				+ " int, " + COL_SURVEY_KEY + " text not null,"
				+ COL_SEQUANCE_NO + " integer, " + COL_TITLE + " text )";
		sqliteDb.execSQL(query);
		printMessage(query);
		return false;
	}

	@Override
	public long insertRow(Pojo obj) {

		return 0;
	}

	@Override
	public void deleteAllData() {
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		db.delete(TABLE, null, null);

	}

}
